﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace TotalApplication.Mine_Video
{
    /// <summary>
    /// TagTreeItem.xaml 的交互逻辑
    /// </summary>
    public partial class TagTreeItem
    {
        public TagTreeItem()
        {
            InitializeComponent();
            this.Loaded += OnControlLoaded;
            this.SizeChanged += OnSizeChanged;
        }

        private void OnControlLoaded(object sender, RoutedEventArgs e)
        {
            Dispatcher.BeginInvoke(DispatcherPriority.Loaded, () =>
            {
                DrawConnections();
            });
        }

        private void OnSizeChanged(object sender, SizeChangedEventArgs e)
        {
            if (IsLoaded)
            {
                DrawConnections();
            }
        }

        private void ChildItemsControl_Loaded(object sender, RoutedEventArgs e)
        {
            DrawConnections();
        }

        #region Old

        //private void DrawConnections()
        //{
        //    try
        //    {
        //        ConnectorCanvas.Children.Clear();

        //        if (ChildItemsControl.Items.Count == 0) return;
        //        if (!IsLoaded) return;

        //        // 获取当前节点的按钮位置（考虑Thickness偏移）
        //        Point parentButtonBottom = GetButtonBottomCenter(NodeButton);

        //        // 为每个子节点绘制连线
        //        for (int i = 0; i < ChildItemsControl.Items.Count; i++)
        //        {
        //            var container = ChildItemsControl.ItemContainerGenerator.ContainerFromIndex(i) as ContentPresenter;
        //            if (container != null)
        //            {
        //                var childControl = FindVisualChild<TagTreeItem>(container);
        //                if (childControl != null && childControl.IsLoaded)
        //                {
        //                    // 获取子节点按钮位置
        //                    Point childButtonTop = GetButtonTopCenter(childControl.NodeButton);

        //                    // 绘制树状连线（第二张图的效果）
        //                    DrawTreeConnection(parentButtonBottom, childButtonTop, i == 0);
        //                }
        //            }
        //        }
        //    }
        //    catch (System.Exception ex)
        //    {
        //        System.Diagnostics.Debug.WriteLine($"DrawConnections error: {ex.Message}");
        //    }
        //}

        //// 关键方法：获取按钮底部中心点（考虑Thickness偏移）
        //private Point GetButtonBottomCenter(Button button)
        //{
        //    // 按钮在父容器中的位置
        //    var buttonPosInParent = button.TranslatePoint(new Point(0, 0), NodeContainer);

        //    // 按钮底部中心点（相对于按钮自身）
        //    var buttonBottomCenter = new Point(button.ActualWidth / 2, button.ActualHeight);

        //    // 转换为Canvas坐标系
        //    var buttonBottomInCanvas = button.TranslatePoint(buttonBottomCenter, ConnectorCanvas);

        //    return buttonBottomInCanvas;
        //}

        //// 获取按钮顶部中心点
        //private Point GetButtonTopCenter(Button button)
        //{
        //    var buttonTopCenter = new Point(button.ActualWidth / 2, 0);
        //    var buttonTopInCanvas = button.TranslatePoint(buttonTopCenter, ConnectorCanvas);
        //    return buttonTopInCanvas;
        //} 


        //private void DrawTreeConnection(Point parentBottom, Point childTop, bool isFirstChild)
        //{
        //    // 计算水平线位置（在父节点下方20像素）
        //    double horizontalLineY = parentBottom.Y + 20;

        //    if (isFirstChild)
        //    {
        //        // 第一个子节点：绘制从父节点到水平线的垂直线
        //        var verticalLine = new Line
        //        {
        //            X1 = parentBottom.X,
        //            Y1 = parentBottom.Y,
        //            X2 = parentBottom.X,
        //            Y2 = horizontalLineY,
        //            Stroke = Brushes.Red,
        //            StrokeThickness = 2
        //        };
        //        ConnectorCanvas.Children.Add(verticalLine);
        //    }

        //    // 绘制水平连接线
        //    var horizontalLine = new Line
        //    {
        //        X1 = parentBottom.X,
        //        Y1 = horizontalLineY,
        //        X2 = childTop.X,
        //        Y2 = horizontalLineY,
        //        Stroke = Brushes.Red,
        //        StrokeThickness = 2
        //    };
        //    ConnectorCanvas.Children.Add(horizontalLine);

        //    // 绘制从水平线到子节点的垂直线
        //    var verticalToChild = new Line
        //    {
        //        X1 = childTop.X,
        //        Y1 = horizontalLineY,
        //        X2 = childTop.X,
        //        Y2 = childTop.Y,
        //        Stroke = Brushes.Red,
        //        StrokeThickness = 2
        //    };
        //    ConnectorCanvas.Children.Add(verticalToChild);

        //    // 添加连接点
        //    AddConnectionPoint(parentBottom.X, horizontalLineY);
        //    AddConnectionPoint(childTop.X, horizontalLineY);
        //}


        //private void AddConnectionPoint(double x, double y)
        //{
        //    var dot = new Ellipse
        //    {
        //        Width = 6,
        //        Height = 6,
        //        Fill = Brushes.Red,
        //        Stroke = Brushes.White,
        //        StrokeThickness = 1
        //    };

        //    Canvas.SetLeft(dot, x - 3);
        //    Canvas.SetTop(dot, y - 3);
        //    ConnectorCanvas.Children.Add(dot);
        //}

        #endregion


        #region New

        private void DrawConnections()
        {
            try
            {
                ConnectorCanvas.Children.Clear();

                if (ChildItemsControl.Items.Count == 0) return;
                if (!IsLoaded) return;

                // 获取当前节点的按钮底部中心点
                Point parentBottomCenter = GetButtonBottomCenter(NodeButton);

                // 为每个子节点绘制精确对齐的连线
                for (int i = 0; i < ChildItemsControl.Items.Count; i++)
                {
                    var container = ChildItemsControl.ItemContainerGenerator.ContainerFromIndex(i) as ContentPresenter;
                    if (container != null)
                    {
                        var childControl = FindVisualChild<TagTreeItem>(container);
                        if (childControl != null && childControl.IsLoaded)
                        {
                            // 获取子节点按钮顶部中心点
                            Point childTopCenter = GetButtonTopCenter(childControl.NodeButton);

                            // 绘制精确对齐的树状连线
                            DrawPreciseTreeConnection(parentBottomCenter, childTopCenter, i, ChildItemsControl.Items.Count);
                        }
                    }
                }
            }
            catch (System.Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"DrawConnections error: {ex.Message}");
            }
        }

        // 精确获取按钮底部中心点（相对于Canvas）
        private Point GetButtonBottomCenter(Button button)
        {
            // 按钮在Canvas中的位置
            var buttonPosInCanvas = button.TranslatePoint(new Point(0, 0), ConnectorCanvas);

            // 按钮底部中心点
            return new Point(buttonPosInCanvas.X + button.ActualWidth / 2 + 2,
                             buttonPosInCanvas.Y + button.ActualHeight);
        }

        // 精确获取按钮顶部中心点
        private Point GetButtonTopCenter(Button button)
        {
            var buttonPosInCanvas = button.TranslatePoint(new Point(0, 0), ConnectorCanvas);
            return new Point(buttonPosInCanvas.X + button.ActualWidth / 2 + 0, buttonPosInCanvas.Y);
        }

        private void DrawPreciseTreeConnection(Point parentBottom, Point childTop, int childIndex, int totalChildren)
        {
            // 水平主干线位置（父节点下方固定距离）
            double horizontalLineY = parentBottom.Y + 20;

            if (childIndex == 0)
            {
                // 第一个子节点：绘制从父节点到水平线的垂直线
                var verticalLine = new Line
                {
                    X1 = parentBottom.X,
                    Y1 = parentBottom.Y,
                    X2 = parentBottom.X,
                    Y2 = horizontalLineY,
                    Stroke = Brushes.Red,
                    StrokeThickness = 2,
                    SnapsToDevicePixels = true
                };
                ConnectorCanvas.Children.Add(verticalLine);
            }

            // 绘制水平连接线（精确对齐）
            var horizontalLine = new Line
            {
                X1 = parentBottom.X,  // 从父节点下方开始
                Y1 = horizontalLineY,
                X2 = childTop.X,      // 到子节点上方结束
                Y2 = horizontalLineY,
                Stroke = Brushes.Red,
                StrokeThickness = 2,
                SnapsToDevicePixels = true
            };
            ConnectorCanvas.Children.Add(horizontalLine);

            // 绘制从水平线到子节点的垂直线（精确对齐）
            var verticalToChild = new Line
            {
                X1 = childTop.X,
                Y1 = horizontalLineY,
                X2 = childTop.X,
                Y2 = childTop.Y,
                Stroke = Brushes.Red,
                StrokeThickness = 2,
                SnapsToDevicePixels = true
            };
            ConnectorCanvas.Children.Add(verticalToChild);
        }

        #endregion





        private static T FindVisualChild<T>(DependencyObject parent) where T : DependencyObject
        {
            if (parent == null) return null;

            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
            {
                var child = VisualTreeHelper.GetChild(parent, i);
                if (child is T result) return result;

                var childResult = FindVisualChild<T>(child);
                if (childResult != null) return childResult;
            }

            return null;
        }
    }
}
